package cn.com.nes.site.service.crm.customer.impl;

import cn.com.nes.common.em.DictTypeEnum;
import cn.com.nes.common.exception.MissBusinessParameterException;
import cn.com.nes.common.util.OssUtil;
import cn.com.nes.common.util.XzqhUtils;
import cn.com.nes.mybatis.agent.crm.entity.*;
import cn.com.nes.mybatis.agent.crm.mapper.CustomerMapper;
import cn.com.nes.mybatis.agent.system.entity.TParam;
import cn.com.nes.mybatis.agent.system.entity.TUser;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.bo.workorder.ReplenishHouseInfoByCustomerBO;
import cn.com.nes.site.entity.em.BusinessType;
import cn.com.nes.site.entity.em.DeleteEnum;
import cn.com.nes.site.entity.em.crm.customer.*;
import cn.com.nes.site.entity.vo.NullVO;
import cn.com.nes.site.entity.vo.crm.*;
import cn.com.nes.site.service.crm.clue.CrmClueService;
import cn.com.nes.site.service.crm.customer.*;
import cn.com.nes.site.service.crm.customer.bo.*;
import cn.com.nes.site.service.crm.customer.dto.*;
import cn.com.nes.site.service.crm.log.LogClaimService;
import cn.com.nes.site.service.crm.log.LogOperateService;
import cn.com.nes.site.service.crm.log.bo.LogOperateBO;
import cn.com.nes.site.service.crm.log.dto.GetLogClaimListDto;
import cn.com.nes.site.service.crm.opportunity.CrmOpportunityService;
import cn.com.nes.site.service.crm.opportunity.bo.QueryOpportunityBO;
import cn.com.nes.site.service.crm.opportunity.dto.OpportunityDTO;
import cn.com.nes.site.service.system.dict.TParamService;
import cn.com.nes.site.service.system.region.XzqhService;
import cn.com.nes.site.service.system.user.SystemUserService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CrmCustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CrmCustomerService {

    private static final BigDecimal DEFAULT_HEATING_LOAD = new BigDecimal(45); // 默认热负荷为 45W

    @Resource
    private CustomerBuilderStrategyFactory customerBuilderStrategyFactory;

    @Resource
    private CrmClueService crmClueService;

    @Resource
    private LogOperateService logOperateService;

    @Resource
    private TParamService tParamService;

    @Resource
    private CustomerHouseService customerHouseService;

    @Resource
    private XzqhService xzqhService;

    @Resource
    private LogClaimService logClaimService;

    @Resource
    private CustomerStaffService customerStaffService;

    @Resource
    private CustomerFileService customerFileService;

    @Resource
    private SystemUserService systemUserService;

    @Resource
    private CrmOpportunityService crmOpportunityService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomerDTO customerSave(CustomerBO customerBO) throws Exception {
        Customer customer = customerBuilderStrategyFactory.getCustomerBuilder(customerBO.getCustomerNature())
                .buildCustomer(customerBO);
        customer.setIsHouseholder(customerBO.getIsHouseholder());
        this.saveOrUpdate(customer);
        customerBO.setUuid(customer.getUuid());

        CustomerDTO customerDTO = new CustomerDTO();
        BeanUtils.copyProperties(customer, customerDTO);

        // 不存在房屋信息，新增房屋信息
        CustomerHouse customerHouse = customerHouseService.getCustomerHouse(customerBO.getXzqhdm(), customerBO.getAddress(), customerBO.getUuid());
        if (ObjectUtil.isNull(customerHouse)) {
            customerHouse = customerHouseService.saveHouseInfo(buildCustomerHouseBo(customerBO));
        } else {
            // 如果存在房屋信息 - 更新房屋信息
            customerHouseService.saveHouseInfo(buildCustomerHouseBo(customerBO, customerHouse));
        }
        customerDTO.setHouseId(customerHouse.getId());
        customerDTO.setHouseUUid(customerHouse.getHouseUuid());

/*        // 不存在客户联系人，新增联系人
        String concat = StrUtil.isNotEmpty(customerBO.getContact()) ? customerBO.getContact() : customerBO.getCustomerName();
        CustomerStaff customerStaff = customerStaffService.getCustomerStaffList(concat, customerBO.getPhone(), customerBO.getUuid());*/
            //创建客户时创建联系人信息
            customerStaffService.saveCustomerStaff(buildCustomerStaffBo(customerBO));

        // 创建客户时创建客户文件
        if (customerBO.hasCustomerFile()) {
            //先删后插
            customerFileService.delCustomerFile(customerBO.getUuid());
            customerFileService.saveCustomerFiles(buildCustomerFileBo(customerBO));
        }

        // 保存 客户操作日志
        LogOperateBO logOperateBO = logOperateService.buildLogOperate(customerBO);
        logOperateService.saveLogOperate(logOperateBO);
        return customerDTO;
    }


    @NotNull
    private List<CustomerFileBO> buildCustomerFileBo(CustomerBO customerBO) throws Exception {
        List<CustomerFileBO> customerFileBOList = new ArrayList<>();
        if (StrUtil.isNotEmpty(customerBO.getIdCardFrontImage())) {
            CustomerFileBO customerFileBO = new CustomerFileBO();
            BeanUtils.copyProperties(customerBO, customerFileBO);
            customerFileBO.setCustomerUuid(customerBO.getUuid());
            customerFileBO.setFileName(customerBO.getCustomerName() + "的身份证正面");
            customerFileBO.setCustomerFileType(CustomerFileTypeEnum._03);
            customerFileBO.setFilePath(customerBO.getIdCardFrontImage());
            customerFileBOList.add(customerFileBO);
        }
        if (StrUtil.isNotEmpty(customerBO.getIdCardBackImage())) {
            CustomerFileBO customerFileBO = new CustomerFileBO();
            BeanUtils.copyProperties(customerBO, customerFileBO);
            customerFileBO.setCustomerUuid(customerBO.getUuid());
            customerFileBO.setFileName(customerBO.getCustomerName() + "的身份证反面");
            customerFileBO.setCustomerFileType(CustomerFileTypeEnum._03);
            customerFileBO.setFilePath(customerBO.getIdCardBackImage());
            customerFileBOList.add(customerFileBO);
        }
        if (StrUtil.isNotEmpty(customerBO.getHouseholdRegistrationBookFirstPageImage())) {
            CustomerFileBO customerFileBO = new CustomerFileBO();
            BeanUtils.copyProperties(customerBO, customerFileBO);
            customerFileBO.setCustomerUuid(customerBO.getUuid());
            customerFileBO.setFileName(customerBO.getCustomerName() + "的户口本首页");
            customerFileBO.setCustomerFileType(CustomerFileTypeEnum._04);
            customerFileBO.setFilePath(customerBO.getHouseholdRegistrationBookFirstPageImage());
            customerFileBOList.add(customerFileBO);
        }
        if (StrUtil.isNotEmpty(customerBO.getHouseholdRegistrationBookHomePageImage())) {
            CustomerFileBO customerFileBO = new CustomerFileBO();
            BeanUtils.copyProperties(customerBO, customerFileBO);
            customerFileBO.setCustomerUuid(customerBO.getUuid());
            customerFileBO.setFileName(customerBO.getCustomerName() + "的户口本户主页");
            customerFileBO.setCustomerFileType(CustomerFileTypeEnum._04);
            customerFileBO.setFilePath(customerBO.getHouseholdRegistrationBookHomePageImage());
            customerFileBOList.add(customerFileBO);
        }
        if (StrUtil.isNotEmpty(customerBO.getJsbyhzhy())) {
            CustomerFileBO customerFileBO = new CustomerFileBO();
            BeanUtils.copyProperties(customerBO, customerFileBO);
            customerFileBO.setCustomerUuid(customerBO.getUuid());
            customerFileBO.setFileName(customerBO.getCustomerName() + "旧设备与户主合影");
            customerFileBO.setCustomerFileType(CustomerFileTypeEnum._05);
            customerFileBO.setFilePath(customerBO.getJsbyhzhy());
            customerFileBOList.add(customerFileBO);
        }
        if (StrUtil.isNotEmpty(customerBO.getSpecialCircumstancesCertificateImage())) {
            CustomerFileBO customerFileBO = new CustomerFileBO();
            BeanUtils.copyProperties(customerBO, customerFileBO);
            customerFileBO.setCustomerUuid(customerBO.getUuid());
            customerFileBO.setFileName(customerBO.getCustomerName() + "特殊情况证明");
            customerFileBO.setCustomerFileType(CustomerFileTypeEnum._06);
            customerFileBO.setFilePath(customerBO.getSpecialCircumstancesCertificateImage());
            customerFileBOList.add(customerFileBO);
        }
        if (StrUtil.isNotEmpty(customerBO.getDbhhwbhzm())) {
            CustomerFileBO customerFileBO = new CustomerFileBO();
            BeanUtils.copyProperties(customerBO, customerFileBO);
            customerFileBO.setCustomerUuid(customerBO.getUuid());
            customerFileBO.setFileName(customerBO.getCustomerName() + "低保户或五保户资格证明");
            customerFileBO.setCustomerFileType(CustomerFileTypeEnum._07);
            customerFileBO.setFilePath(customerBO.getDbhhwbhzm());
            customerFileBOList.add(customerFileBO);
        }
        return customerFileBOList;
    }

    @NotNull
    private CustomerStaffBO buildCustomerStaffBo(CustomerBO bo) {
        if(StrUtil.isNotEmpty(bo.getIsHouseholder())) {
            CustomerStaffBO customerStaffBO = new CustomerStaffBO();
            if(StrUtil.isNotEmpty(bo.getCustomerStaffId())){
                customerStaffBO.setId(Long.parseLong(bo.getCustomerStaffId()));
                customerStaffBO.setCustomerUuid(bo.getUuid());
            }else {
                customerStaffBO.setCustomerUuid(bo.getUuid());
            }
            customerStaffBO.setPhone(bo.getPhoneNow());
            customerStaffBO.setName(bo.getCustomerNameNow());
            customerStaffBO.setOperateUserId(bo.getOperateUserId());
            customerStaffBO.setOperateDate(bo.getOperateDate());
            customerStaffBO.setIsMain(1);
            customerStaffBO.setXzqhdm(bo.getXzqhdm());
            customerStaffBO.setSfzh(bo.getIdCardNumberNow());
            //是否联系人已经有户主了，如果有户主了，就不能是户主了
            customerStaffBO.setIsHousehold(1);
            return customerStaffBO;
        }else{
            customerStaffService.getHouseholdCustomerStaff(bo.getUuid());
            CustomerStaffBO customerStaffBO = new CustomerStaffBO();
            customerStaffBO.setCustomerUuid(bo.getUuid());
            customerStaffBO.setPhone(bo.getPhone());
            customerStaffBO.setName(StrUtil.isNotEmpty(bo.getContact()) ? bo.getContact() : bo.getCustomerName());
            customerStaffBO.setOperateUserId(bo.getOperateUserId());
            customerStaffBO.setOperateDate(bo.getOperateDate());
            customerStaffBO.setIsMain(1);
            customerStaffBO.setXzqhdm(bo.getXzqhdm());
            customerStaffBO.setSfzh(bo.getIdCardNumber());
            //是否联系人已经有户主了，如果有户主了，就不能是户主了1是0不是
            if(ObjectUtil.isNotNull(customerStaffService.getHouseholdCustomerStaff(bo.getUuid()))){
                customerStaffBO.setIsHousehold(0);
            }else{
                customerStaffBO.setIsHousehold(1);
            }
            return customerStaffBO;
        }


    }

    @NotNull
    private CustomerHouseVO buildCustomerHouseBo(CustomerBO bo) {
        CustomerHouseVO customerHouseVO = new CustomerHouseVO();
        customerHouseVO.setCustomerId(bo.getUuid());
        customerHouseVO.setAreaCode(bo.getXzqhdm());
        customerHouseVO.setAddress(bo.getAddress());
        customerHouseVO.setUserInfo(bo.getUserInfo());
        customerHouseVO.setDesignHeatingLoad(DEFAULT_HEATING_LOAD); // 默认热负荷
        customerHouseVO.setIsVillage(null); // 是否农村
        customerHouseVO.setHeatingArea(bo.getHeatingArea());
        customerHouseVO.setFloorSpace(bo.getFloorSpace());
        customerHouseVO.setCommonHeatingArea(bo.getCommonHeatingArea());
        customerHouseVO.setHouseNumber(bo.getHouseNumber());
        if (ObjectUtil.isNotNull(bo.getEnergyType())) {
            customerHouseVO.setEnergyType(String.valueOf(bo.getEnergyType().getKey()));
        }
        if (StrUtil.isNotEmpty(bo.getElectricityMeterNumber())) {
            customerHouseVO.setElectricityMeterNumber(bo.getElectricityMeterNumber());
        }
        if (StrUtil.isNotEmpty(bo.getGasMeterNumber())) {
            customerHouseVO.setGasMeterNumber(bo.getGasMeterNumber());
        }

        customerHouseVO.setHouseType(String.valueOf(bo.getBuildingType()));
        customerHouseVO.setOperateUserId(bo.getOperateUserId());
        customerHouseVO.setOperateUserCompanyId(bo.getOperateUserCompanyId());
        return customerHouseVO;
    }

    @NotNull
    private CustomerHouseVO buildCustomerHouseBo(CustomerBO bo, CustomerHouse customerHouse) {
        CustomerHouseVO customerHouseVO = new CustomerHouseVO();
        BeanUtils.copyProperties(customerHouse, customerHouseVO);
        customerHouseVO.setCustomerId(bo.getUuid());
        customerHouseVO.setAreaCode(bo.getXzqhdm());
        customerHouseVO.setAddress(bo.getAddress());
        customerHouseVO.setUserInfo(bo.getUserInfo());
        customerHouseVO.setDesignHeatingLoad(DEFAULT_HEATING_LOAD); // 默认热负荷
        customerHouseVO.setIsVillage(null); // 是否农村
        customerHouseVO.setHeatingArea(bo.getHeatingArea());
        customerHouseVO.setFloorSpace(bo.getFloorSpace());
        customerHouseVO.setCommonHeatingArea(bo.getCommonHeatingArea());
        customerHouseVO.setHouseNumber(bo.getHouseNumber());
        if (ObjectUtil.isNotNull(bo.getEnergyType())) {
            customerHouseVO.setEnergyType(String.valueOf(bo.getEnergyType().getKey()));
        }
        if (StrUtil.isNotEmpty(bo.getElectricityMeterNumber())) {
            customerHouseVO.setElectricityMeterNumber(bo.getElectricityMeterNumber());
        }
        if (StrUtil.isNotEmpty(bo.getGasMeterNumber())) {
            customerHouseVO.setGasMeterNumber(bo.getGasMeterNumber());
        }

        customerHouseVO.setHouseType(String.valueOf(bo.getBuildingType()));
        customerHouseVO.setOperateUserId(bo.getOperateUserId());
        customerHouseVO.setOperateUserCompanyId(bo.getOperateUserCompanyId());
        return customerHouseVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CustomerDTO saveCrmCustomer(SaveCustomerVo vo) throws Exception {
        return customerSave(vo.convertToBo());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData clueToCustomer(ClueToCustomerVo vo) throws Exception {
        for (String clueId : vo.getClueId()) {
            // 转客户成功后，更新线索表，记录客户ID
            Clue clue = crmClueService.getById(clueId);

            // 保存客户
            CustomerDTO customerDTO = customerSave(buildCustomer(vo, clue).convertToBo());

            // 更新线索，线索记录客户UUID
            clue.setCustomerId(customerDTO.getUuid());
            clue.setModifyUid(vo.getOperateUserId());
            clue.setModifyTime(vo.getOperateDate());
            crmClueService.updateById(clue);
        }
        return PageData.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData assignCustomers(AssignCustomersVo vo) throws Exception {
        for (String customerId : vo.getCustomerIds()) {
            Customer customer = this.baseMapper.selectById(customerId);
            customer.setCustomerOwnerId(vo.getCustomerOwnerId());
            customer.setModifyTime(vo.getOperateDate());
            customer.setModifyUid(vo.getOperateUserId().toString());
            this.baseMapper.updateById(customer);

            // 记录操作信息
            LogOperate logOperate = new LogOperate();
            logOperate.setUuid(UUID.randomUUID().toString());
            logOperate.setCreatetime(vo.getOperateDate());
            logOperate.setUserid(vo.getOperateUserId().toString());
            logOperate.setUsername(vo.getOperateUserName());
            logOperate.setCompanyid(vo.getOperateUserCompanyId());
            logOperate.setMemo(vo.getUserInfo().getCompanyName() + " " + vo.getOperateUserName() + "分配了客户");
            logOperate.setRemark("分配客户");
            logOperate.setType("02");
            logOperate.setCustomerid(customerId);
            logOperateService.save(logOperate);
        }
        return PageData.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData claimCustomer(ClaimCustomerVo vo) throws Exception {
        Customer customer = this.getCustomer(vo.getCustomerId());
        customer.setCustomerOwnerId(vo.getOperateUserId());
        customer.setModifyTime(vo.getOperateDate());
        customer.setModifyUid(vo.getOperateUserId().toString());
        this.saveOrUpdate(customer);

        // 记录操作信息
        LogOperate logOperate = new LogOperate();
        logOperate.setUuid(UUID.randomUUID().toString());
        logOperate.setCreatetime(vo.getOperateDate());
        logOperate.setUserid(vo.getOperateUserId().toString());
        logOperate.setUsername(vo.getOperateUserName());
        logOperate.setCompanyid(vo.getOperateUserCompanyId());
        logOperate.setMemo(vo.getUserInfo().getCompanyName() + " " + vo.getOperateUserName() + "领取了客户");
        logOperate.setType("02");
        logOperate.setRemark("领取客户");
        logOperate.setCustomerid(vo.getCustomerId());
        logOperateService.save(logOperate);

        return PageData.ok();

    }

    private Customer getCustomer(String customerUuid) throws Exception {
        if (StrUtil.isEmpty(customerUuid)) {
            throw new MissBusinessParameterException("customerUuid can not be empty");
        }
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("uuid", customerUuid);
        wrapper.eq("`isdelete`", DeleteEnum._0.getKey());
        return this.getOne(wrapper);
    }

    @Override
    public CustomerDTO getCustomerByPhone(String phone,String companyId) {
        Customer customerVo = new Customer();
        customerVo.setPhone(phone);
        customerVo.setCompanyId(companyId);
        Customer customer = this.baseMapper.getCustomerByPhone(customerVo);
        if (ObjectUtil.isNull(customer)) {
            return null;
        }

        CustomerDTO customerDTO = new CustomerDTO();
        BeanUtils.copyProperties(customer, customerDTO);
        return customerDTO;
    }

    @Override
    public CustomerDTO getCustomerByIdCard(HashMap<String, Object> hashMap) {
        Customer customer = this.baseMapper.getCustomerByIdCard(hashMap.get("idCardNumber")
                .toString(), hashMap.get("projectUuid").toString(), hashMap.get("xzqhdm")
                .toString(), hashMap.get("customerName").toString(), hashMap.get("phone").toString());
        if (ObjectUtil.isNull(customer)) {
            return null;
        }
        CustomerDTO customerDTO = new CustomerDTO();
        BeanUtils.copyProperties(customer, customerDTO);
        return customerDTO;
    }


    @Override
    public CustomerDTO getCustomerById(String uuid) {
        Customer customerVo = new Customer();
        customerVo.setUuid(uuid);
        customerVo.setDeleted("0"); // 没删除
        Customer customer = this.baseMapper.selectOne(new QueryWrapper<Customer>(customerVo));

        CustomerDTO customerDTO = new CustomerDTO();
        if (ObjectUtil.isNull(customer)) {
            return customerDTO;
        }
        BeanUtils.copyProperties(customer, customerDTO);
        setCustomerDetailFields(customerDTO);
        return customerDTO;
    }

    @Override
    public Page<Customer> customerPage(CustomerPageBO bo) throws Exception {
        Page<Customer> page = new Page<>(bo.getPageid(), bo.getPagesize());
        List<Customer> customers = this.baseMapper.customerPage(page, bo);

        List<TParam> customerNatureParams = tParamService.getList("20");
        Map<String, TParam> customerNatureParamsMap = customerNatureParams.stream()
                .collect(Collectors.toMap(TParam::getValue, t -> t));
        List<TParam> businessTypeParams = tParamService.getList("21");
        Map<String, TParam> businessTypeParamsMap = businessTypeParams.stream()
                .collect(Collectors.toMap(TParam::getValue, t -> t));
        List<TParam> customerLevelParams = tParamService.getList("22");
        Map<String, TParam> customerLevelParamsMap = customerLevelParams.stream()
                .collect(Collectors.toMap(TParam::getValue, t -> t));

        List<TParam> customerSourceParams = tParamService.getList("13");
        Map<String, TParam> customerSourceParamsMap = customerSourceParams.stream()
                .collect(Collectors.toMap(TParam::getValue, t -> t));

        List<TUser> users = systemUserService.getUsers(customers.stream()
                .map(Customer::getCustomerOwnerId)
                .collect(Collectors.toList()));
        Map<Long, TUser> userMap = users.stream().collect(Collectors.toMap(TUser::getId, t -> t));

        for (Customer customer : customers) {
            if (ObjectUtil.isNotEmpty(customer.getCustomerOwnerId())) {
                customer.setCustomerOwnerName(userMap.get(customer.getCustomerOwnerId()).getNickName());
            }

            if (StrUtil.isNotEmpty(customer.getCustomerNature())) {
                customer.setCustomerNatureName(customerNatureParamsMap.get(customer.getCustomerNature()).getName());
            }
            if (StrUtil.isNotEmpty(customer.getBusinessType())) {
                customer.setBusinessTypeName(businessTypeParamsMap.get(customer.getBusinessType()).getName());
            }
            if (StrUtil.isNotEmpty(customer.getCustomerLevel())) {
                customer.setCustomerLevelName(customerLevelParamsMap.get(customer.getCustomerLevel()).getName());
            }
            if (StrUtil.isNotEmpty(customer.getCustomerSource())) {
                customer.setCustomerSourceName(customerSourceParamsMap.get(customer.getCustomerSource()).getName());
            }
            QueryOpportunityBO queryOpportunityBO = new QueryOpportunityBO();
            queryOpportunityBO.setCustomerUuid(customer.getUuid());
            List<Opportunity> opportunities = crmOpportunityService.getOpportunities(queryOpportunityBO);
            customer.setOppoCount(opportunities.size());
        }
        page.setRecords(customers);
        return page;
    }

    @Override
    public List<String> getCustomerIdListByAreaCode(String areaCode, Long projectId) {
        // 入参校验
        if (StrUtil.isBlank(areaCode)) {
            return Collections.emptyList();
        }
        // 取出行政区划代码的有效位
        return this.baseMapper.getCustomerIdListByAreaCode(XzqhUtils.getRegionCodePrefix(areaCode), projectId);
    }

    @Override
    public CustomerDetailDTO getCustomerDetail(GetCustomerDetailBO bo) throws Exception {
        CustomerDetailDTO customerDetailDTO = new CustomerDetailDTO();
        customerDetailDTO.setCustomerInfo(getCustomerInfoDto(bo));
        customerDetailDTO.setCustomerHouseList(getCustomerHouseList(bo));
        customerDetailDTO.setClaimList(getCustomerClaimDtoList(bo));
        customerDetailDTO.setStaffList(getCustomerStaffDtoList(bo));
        customerDetailDTO.setOpportunityList(getCustomerOpportunityDtoList(bo));
        customerDetailDTO.setFileList(getCustomerFileDtoList(bo));
        return customerDetailDTO;
    }

    //获取客户跟进记录
    private List<GetLogClaimListDto> getCustomerClaimDtoList(GetCustomerDetailBO bo) {
        GetLogClaimListBo logClaimListBo = new GetLogClaimListBo();
        logClaimListBo.setCustomerId(bo.getCustomerId());
        logClaimListBo.setClaimType("02");
        return logClaimService.getLogClaimList(logClaimListBo);
    }

    //获取客户联系人
    private List<CustomerStaffDTO> getCustomerStaffDtoList(GetCustomerDetailBO bo) {
        CustomerStaffBO customerStaffBo = new CustomerStaffBO();
        customerStaffBo.setCustomerUuid(bo.getCustomerId());
        return customerStaffService.getCustomerStaffList(customerStaffBo);
    }


    //获取商机列表
    private List<OpportunityDTO> getCustomerOpportunityDtoList(GetCustomerDetailBO bo) {
        CustomerOpportunityBo customerOpportunityBo = new CustomerOpportunityBo();
        customerOpportunityBo.setCustomerId(bo.getCustomerId());
        return crmOpportunityService.getCustomerOpportunityList(customerOpportunityBo);
    }

    //获取客户文件列表
    private List<CustomerFileDTO> getCustomerFileDtoList(GetCustomerDetailBO bo) {
        CustomerFileBO customerFileBo = new CustomerFileBO();
        customerFileBo.setCustomerUuid(bo.getCustomerId());
        List<CustomerFileDTO> customerFileList = customerFileService.getCustomerFileList(customerFileBo);
        //获取客户文件真实路径
        Iterator<CustomerFileDTO> iterator = customerFileList.iterator();
        while (iterator.hasNext()) {
            CustomerFileDTO next = iterator.next();
            String filepath = next.getFilePath();
            String imgSignURL = OssUtil.getFileSignURL(filepath, 0);
            next.setRealFilePath(imgSignURL);
        }
        return customerFileList;
    }

    //获取客户详情
    private CustomerInfoDTO getCustomerInfoDto(GetCustomerDetailBO bo) throws Exception {
        Customer customer = this.getCustomer(bo.getCustomerId());
        CustomerInfoDTO customerInfoDto = new CustomerInfoDTO();
        if (ObjectUtil.isNull(customer)) {
            return customerInfoDto;
        }
        if (ObjectUtil.isNotNull(customer.getCustomerOwnerId())) {
            customer.setCustomerOwnerName(systemUserService.getUserInfoByUserId(customer.getCustomerOwnerId()
                    .toString()).getNickName());
        }
        BeanUtils.copyProperties(customer, customerInfoDto);

        customerInfoDto.setCustomerOwnerId(customer.getCustomerOwnerId());
        customerInfoDto.setVillagers(String.valueOf(customer.getVillagers()));
        if(ObjectUtil.isNotNull(customerStaffService.getHouseholdCustomerStaff(customer.getUuid()))) {
            CustomerStaffDTO customerStaffDTO = customerStaffService.getHouseholdCustomerStaff(customer.getUuid());
            customerInfoDto.setCustomerNameNow(customerStaffDTO.getName());
            customerInfoDto.setPhoneNow(customerStaffDTO.getPhone());
            customerInfoDto.setIdCardNumberNow(customerStaffDTO.getSfzh());
            customerInfoDto.setCustomerStaffId(customerStaffDTO.getId());
        }
        setCustomerInfoFields(customerInfoDto);
        return customerInfoDto;
    }

    //客户房屋信息
    private List<CustomerHouseDTO> getCustomerHouseList(GetCustomerDetailBO bo) throws Exception {
        GetCustomerHousePageVO getCustomerHousePageVO = new GetCustomerHousePageVO();
        getCustomerHousePageVO.setCustomerUuid(bo.getCustomerId());
        return customerHouseService.getCustomerHouse(getCustomerHousePageVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData replenishCustomerInfo(ReplenishCustomerInfoVO vo) throws Exception {
        // 客户表更新数据
        Integer rows = this.baseMapper.replenishCustomerInfo(vo);
        if (1 != rows) {
            throw new Exception("补充客户信息失败!");
        }

        // 补充房屋信息
        ReplenishHouseInfoByCustomerBO bo = new ReplenishHouseInfoByCustomerBO();
        BeanUtils.copyProperties(vo, bo);
        customerHouseService.replenishHouseInfoByCustomer(bo);

        return PageData.ok();
    }

    @Override
    public PageData replenishCustomerDropdownBox(NullVO vo) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put(DictTypeEnum.ENERGY_USE_PROPERTY.getTypeNameEN(), tParamService.getListMap(DictTypeEnum.ENERGY_USE_PROPERTY.getParamType()));

        return PageData.ok(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<String> ids, Long operateUserId, Date operateDate) throws Exception {
        if (CollUtil.isEmpty(ids)) {
            throw new MissBusinessParameterException("请传入要删除的客户ID");
        }
        this.baseMapper.deleteByIds(ids, operateUserId, operateDate);
    }

    @Override
    public List<String> getCustomerIdListByCustomerName(String customerName) {
        return this.baseMapper.getCustomerIdListByCustomerName(customerName);
    }

    @Override
    public Customer getCustomerByIdCardNumber(String companyId, String idCardNumber) throws Exception {
        if (StrUtil.isEmpty(companyId)) {
            throw new MissBusinessParameterException("companyId can not be empty");
        }
        if (StrUtil.isEmpty(idCardNumber)) {
            throw new MissBusinessParameterException("idCardNumber can not be empty");
        }
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("company_id", companyId);
        wrapper.eq("id_card_number", idCardNumber);
        wrapper.eq("`isdelete`", DeleteEnum._0.getKey());
        return this.getOne(wrapper);
    }

    @Override
    public Customer onlySaveCustomer(CustomerBO bo) throws Exception {
        // 根据手机号和公司代码查询客户信息
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", bo.getOperateUserCompanyId());
        queryWrapper.eq("mer_customer_id", bo.getMerCustomerId());
        queryWrapper.eq("isdelete", false);
        queryWrapper.last("limit 1");
        List<Customer> customers = this.baseMapper.selectList(queryWrapper);

        // 更新或新增客户信息
        if (CollectionUtil.isNotEmpty(customers)) {
            return customers.get(0);
        }
        Customer customer = new Customer();
        BeanUtils.copyProperties(bo, customer);
        customer.setCustomerNature(ObjectUtil.isNotNull(bo.getCustomerNature()) ? bo.getCustomerNature().getKey() : CustomerNatureEnum._personal.getKey());
        customer.setCustomerLevel(ObjectUtil.isNotNull(bo.getCustomerLevel()) ? bo.getCustomerLevel().getType() : CustomerLevelEnum._level_5.getType());
        customer.setClueId(bo.getClueId());
        customer.setUuid(IdUtil.randomUUID());
        customer.setCompanyId(bo.getOperateUserCompanyId());
        customer.setMerCustomerId(bo.getMerCustomerId());
        customer.setCreateTime(new Date());
        customer.setModifyTime(new Date());
        customer.setDeleted(String.valueOf(DeleteEnum._0.getKey()));
        boolean success = this.save(customer);
        if (!success) {
            throw new Exception("新增客户信息失败!");
        }
        return customer;
    }

    @NotNull
    private SaveCustomerVo buildCustomer(ClueToCustomerVo vo, Clue clue) {
        SaveCustomerVo saveCustomerVo = new SaveCustomerVo();
        saveCustomerVo.setCustomerName(clue.getCompanyContact());
        saveCustomerVo.setPhone(clue.getCluePhone());
        saveCustomerVo.setCustomerNature(StrUtil.isNotEmpty(clue.getCustomerNature()) ? CustomerNatureEnum.getEnum(clue.getCustomerNature())
                .getKey() : CustomerNatureEnum._other.getKey());
        saveCustomerVo.setContact(clue.getCompanyContact());
        saveCustomerVo.setLongitude(Objects.isNull(clue.getCustomerJd()) ? null : BigDecimal.valueOf(clue.getCustomerJd()));
        saveCustomerVo.setLatitude(Objects.isNull(clue.getCustomerWd()) ? null : BigDecimal.valueOf(clue.getCustomerWd()));
        saveCustomerVo.setOperateDate(vo.getOperateDate());
        saveCustomerVo.setOperateUserId(vo.getOperateUserId());
        saveCustomerVo.setOperateUserCompanyId(vo.getOperateUserCompanyId());
        saveCustomerVo.setUserInfo(vo.getUserInfo());
        saveCustomerVo.setOperatePlatform(vo.getOperatePlatform());
        saveCustomerVo.setAddress(clue.getCustomerAddress());
        saveCustomerVo.setXzqhdm(clue.getXzqhdm());
        return saveCustomerVo;
    }

    private void convertParamsToDbQuery(QueryCustomerPageVo vo) {
        // 获取行政区划查询参数
        vo.setXzqhdm(XzqhUtils.getRegionCodePrefix(vo.getXzqhdm()));
    }

    private void setCustomerDetailFields(CustomerDTO customerDetail) {
        customerDetail.setAreaName(xzqhService.getAreaName(customerDetail.getXzqhdm()));
        customerDetail.setEnergyUseProperty(tParamService.getNameByParamTypeAndValue(DictTypeEnum.ENERGY_USE_PROPERTY.getParamType(), customerDetail.getEnergyUsePropertyCode()));
    }

    private void setCustomerInfoFields(CustomerInfoDTO customerInfoDto) {
        customerInfoDto.setXzqhmc(xzqhService.getAreaName(customerInfoDto.getXzqhdm()));
        customerInfoDto.setCustomerNatureName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.CUSTOMER_NATURE.getParamType(), customerInfoDto.getCustomerNature()));
        customerInfoDto.setBusinessTypeName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.BUSINESS_TYPE.getParamType(), customerInfoDto.getBusinessType()));
        customerInfoDto.setCustomerLevelName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.CUSTOMER_LEVEL.getParamType(), customerInfoDto.getCustomerLevel()));
        customerInfoDto.setDistributorTypeName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.DISTRIBUTOR_TYPE.getParamType(), customerInfoDto.getDistributorType()));
        customerInfoDto.setNatureOfCompanyName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.NATUREOF_COMPANY.getParamType(), customerInfoDto.getNatureOfCompany()));
        customerInfoDto.setCustomerSourceName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.CUSTOMER_SOURCE.getParamType(), customerInfoDto.getCustomerSource()));
        customerInfoDto.setEnergyUsePropertyCodeName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.ENERGY_USE_PROPERTY.getParamType(), customerInfoDto.getEnergyUsePropertyCode()));
        customerInfoDto.setVillagersName(tParamService.getNameByParamTypeAndValue(DictTypeEnum.WHETHER.getParamType(), customerInfoDto.getVillagers()));
    }

}
